<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>应急管理 - 教师端</title>
  <link rel="icon" type="image/ico" href="pc/ico.png">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Microsoft YaHei', '微软雅黑', sans-serif;
      background-color: #f5f5f5;
      color: #333;
      line-height: 1.6;
    }

    .header {
      background: linear-gradient(135deg, #4e79ff 0%, #a0c4ff 100%);
      color: white;
      padding: 2rem;
      text-align: center;
    }

    .header h1 {
      font-size: 2rem;
      margin-bottom: 0.5rem;
    }

    .header p {
      font-size: 1rem;
      opacity: 0.9;
    }

    .menu-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
      gap: 1rem;
      padding: 1rem;
      background-color: white;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .menu-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-decoration: none;
      color: #333;
      padding: 1rem;
      border-radius: 8px;
      transition: all 0.3s ease;
    }

    .menu-item:hover {
      background-color: #e6f0ff;
      transform: translateY(-5px);
    }

    .menu-icon {
      font-size: 2rem;
      margin-bottom: 0.5rem;
    }

    .section {
      background-color: white;
      margin: 1rem;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 1rem;
      background-color: #e6f0ff;
      border-bottom: 1px solid #cce0ff;
    }

    .section-title {
      font-size: 1.2rem;
      font-weight: bold;
      color: #4e79ff;
    }

    .more-link {
      color: #4e79ff;
      text-decoration: none;
      font-size: 0.9rem;
    }

    .card-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 1rem;
      padding: 1rem;
      overflow-x: hidden; /* 防止内容溢出 */
    }

    .card {
      background-color: #fff;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s;
    }

    .card:hover {
      transform: translateY(-5px);
    }

    .card img {
      width: 100%;
      height: 150px;
      object-fit: cover;
    }

    .card-content {
      padding: 1rem;
    }

    .card-title {
      font-size: 1rem;
      font-weight: bold;
      margin-bottom: 0.5rem;
      color: #4e79ff;
    }

    .card-description {
      font-size: 0.9rem;
      color: #666;
    }


    /* 模态框样式 */
    .modal {
      display: none; /* 初始状态隐藏 */
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
      justify-content: center;
      align-items: center;
      z-index: 1000;
    }

    .modal-content {
      background-color: #fff;
      padding: 1.5rem;
      border-radius: 8px;
      max-width: 400px;
      width: 90%;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      text-align: center;
    }

    .modal-content h3 {
      margin-bottom: 1rem;
      font-size: 1.2rem;
      color: #4e79ff;
    }

    .modal-content button {
      background-color: #4e79ff;
      color: white;
      border: none;
      padding: 0.5rem 1rem;
      margin: 0.5rem;
      cursor: pointer;
      font-size: 1rem;
      border-radius: 5px;
      transition: background-color 0.3s;
    }

    .modal-content button:hover {
      background-color: #3a5dd0;
    }

    .modal-content .cancel-btn {
      background-color: #ccc;
      color: #333;
    }

    .modal-content .cancel-btn:hover {
      background-color: #b3b3b3;
    }

    .pagination-buttons {
      display: flex;
      justify-content: space-between;
      padding: 1rem;
    }

    .pagination-button {
      background-color: #4e79ff;
      color: white;
      border: none;
      padding: 0.5rem 1rem;
      cursor: pointer;
      border-radius: 5px;
      font-size: 0.9rem;
      display: inline-block;
      text-align: center;
    }

    .pagination-button:disabled {
      background-color: #ddd;
      cursor: not-allowed;
    }

    .no-more-posts {
      text-align: center;
      font-size: 1rem;
      color: #999;
      padding: 1rem;
    }

    /* 公告弹窗样式 */
    .announcement-modal {
      display: none; /* 初始隐藏 */
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
      justify-content: center;
      align-items: center;
      z-index: 1000;
    }

    .announcement-content {
      background-color: #fff;
      padding: 2rem;
      border-radius: 10px;
      max-width: 300px;
      width: 80%;
      text-align: center;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      position: relative;
    }

    .close-btn {
      position: absolute;
      top: 10px;
      right: 10px;
      background: none;
      border: none;
      font-size: 1.5rem;
      cursor: pointer;
      color: #999;
    }

    .close-btn:hover {
      color: #333;
    }

    .announcement-title {
      font-size: 1.5rem;
      color: #333;
      margin-bottom: 1rem;
    }

    .announcement-text {
      font-size: 1rem;
      color: #666;
      margin-bottom: 1.5rem;
      line-height: 1.5;
    }

    .announcement-link {
      display: inline-block;
      color: #888;
      font-size: 0.9rem;
      text-decoration: underline;
      cursor: pointer;
    }

    .announcement-link:hover {
      color: #333;
    }
  </style>
</head>
<body>
<header class="header">
  <h1>应急管理 - 教师端</h1>
  <p>引领教学，培养未来</p>
</header>

<nav class="menu-grid">
  <a href="/teacher_dashboard.html" class="menu-item">
    <span class="menu-icon">🎓</span>
    <span>导师计划</span>
  </a>
  <a href="/course_management.html" class="menu-item">
    <span class="menu-icon">📚</span>
    <span>课程管理</span>
  </a>
  <a href="/student_management.html" class="menu-item">
    <span class="menu-icon">👥</span>
    <span>学生管理</span>
  </a>
  <a href="/exam_management.html" class="menu-item">
    <span class="menu-icon">✏️</span>
    <span>考试管理</span>
  </a>
  <a href="/teaching_resources.html" class="menu-item">
    <span class="menu-icon">📖</span>
    <span>教学资源</span>
  </a>
  <a href="#" class="menu-item" onclick="openSubjectModal()"> <!-- 点击显示模态框 -->
    <div class="menu-icon">📝</div>
    <span class="menu-label">创建考试</span>
  </a>
  <a href="/resource_exploration.html" class="menu-item">
    <span class="menu-icon">🔍</span>
    <span>资源探索</span>
  </a>
</nav>

<section class="section">
  <div class="section-header">
    <h2 class="section-title">最新资讯</h2>
    <div class="pagination-buttons">
      <button class="pagination-button" id="prevPage" onclick="loadPreviousPage()" disabled>< 上一页</button>
      <button class="pagination-button" id="nextPage" onclick="loadNextPage()">下一页 ></button>
    </div>
  </div>
  <div class="card-grid" id="postGrid"> <!-- 设置id用于JS插入内容 -->
    <!-- 推文数据将被动态插入到这里 -->
  </div>
</section>

<section class="section">
  <div class="section-header">
    <h2 class="section-title">教学资源推荐</h2>
    <a href="/more_teaching_resources.html" class="more-link">探索更多 ></a>
  </div>
  <div class="card-grid">
    <div class="card">
      <img src="https://th.bing.com/th/id/R.567ae2c9aa24e7bd36d8b447b14e0ab0?rik=o1kdeCqFrdgCUw&riu=http%3a%2f%2fimg.netbian.com%2ffile%2f2023%2f1022%2f210232lVk42.jpg&ehk=UWFW0wv%2bsKclaMhk3zrb7N%2btYU5M8pxo8kS2qYgHDRA%3d&risl=&pid=ImgRaw&r=0"
           alt="教学管理">
      <div class="card-content">
        <h3 class="card-title">教学管理系统</h3>
        <p class="card-description">高效管理课程、学生和教学资源，提升教学质量。</p>
      </div>
    </div>
    <div class="card">
      <img src="https://th.bing.com/th/id/R.567ae2c9aa24e7bd36d8b447b14e0ab0?rik=o1kdeCqFrdgCUw&riu=http%3a%2f%2fimg.netbian.com%2ffile%2f2023%2f1022%2f210232lVk42.jpg&ehk=UWFW0wv%2bsKclaMhk3zrb7N%2btYU5M8pxo8kS2qYgHDRA%3d&risl=&pid=ImgRaw&r=0"
           alt="在线资源">
      <div class="card-content">
        <h3 class="card-title">在线教学资源</h3>
        <p class="card-description">丰富的教学资料，助力教师备课和学生学习。</p>
      </div>
    </div>
  </div>
</section>

<!-- 公告弹窗 HTML -->
<div id="announcementModal" class="announcement-modal">
  <div class="announcement-content">
    <button class="close-btn" onclick="closeAnnouncementModal()">×</button>
    <h3 class="announcement-title">网站通知</h3>
    <p id="announcementTitle" class="announcement_title"></p>
    <p id="announcementContent" class="announcement-text"></p>
    <a href="#" class="announcement-link" onclick="closeAnnouncementModal()">有问题及时反馈！</a>
  </div>
</div>

<!-- 弹出模态框 HTML -->
<div id="subjectModal" class="modal">
  <div class="modal-content">
    <h3>请选择考试类型</h3>
    <button onclick="selectExamType('理论')">理论考试</button>
    <button onclick="selectExamType('实操')">实操考试</button>
    <button class="cancel-btn" onclick="closeSubjectModal()">取消</button>
  </div>
</div>

<script>
  // 检查教师登录状态
  async function checkLoginStatus() {
    try {
      const response = await fetch('/api/v1/users/getUserInfo', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const result = await response.json();
      if (result.code !== 200 || !result.data.username) {
        // 如果未登录，则跳转到教师登录页面
        window.location.href = '/login.html';
      }
    } catch (error) {
      console.error("登录检测失败", error);
      window.location.href = '/login.html'; // 出错时也跳转到登录页面
    }
  }

  // 打开模态框
  function openSubjectModal() {
    document.getElementById('subjectModal').style.display = 'flex';
  }

  // 关闭模态框
  function closeSubjectModal() {
    document.getElementById('subjectModal').style.display = 'none';
  }

  // 选择考试类型
  function selectExamType(type) {
    window.location.href = `/create_exam.html?type=${encodeURIComponent(type)}`;
    closeSubjectModal();
  }

  let currentPage = 1;
  const pageSize = 3;
  let isLoading = false; // 防止多次触发加载

  // 使用 JavaScript 获取推文数据并插入到 HTML 中
  async function fetchPosts(pageNum = 1, pageSize = 3) {
    const url = `/api/v1/posts/paged?pageNum=${pageNum}&pageSize=${pageSize}`;
    try {
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        const result = await response.json();
        if (result.code === 200) {
          if (Array.isArray(result.data) && result.data.length > 0) {
            renderPosts(result.data); // 渲染获取到的推文
            isLoading = false; // 数据加载完成后，允许继续加载
          } else {
            showNoMorePosts(); // 显示无更多文章提示
            isLoading = false;
          }
          updatePaginationButtons(); // 更新按钮状态
        } else {
          console.error("数据格式错误", result);
        }
      } else {
        console.error("请求失败", response.status);
      }
    } catch (error) {
      console.error("网络请求错误", error);
    }
  }

  // 渲染推文数据到页面上
  function renderPosts(posts) {
    const postGrid = document.getElementById('postGrid');
    postGrid.innerHTML = ''; // 清空现有内容，覆盖旧内容

    posts.forEach(post => {
      const {postId, title, coverUrl, content, createdAt} = post;
      const shortContent = content.length > 50 ? content.substring(0, 50) + '...' : content;
      const formattedDate = new Date(createdAt).toLocaleString();

      const cardHtml = `
                <div class="card" onclick="goToPostDetail(${postId})">
                    <img src="${coverUrl}" alt="Post image">
                    <div class="card-content">
                        <h3 class="card-title">${title}</h3>
                        <p class="card-description">${shortContent}</p>
                        <p class="card-description"><small>发布时间: ${formattedDate}</small></p>
                    </div>
                </div>
            `;
      postGrid.insertAdjacentHTML('beforeend', cardHtml);
    });
  }

  // 显示无更多文章的提示
  function showNoMorePosts() {
    const postGrid = document.getElementById('postGrid');
    postGrid.innerHTML = '<div class="no-more-posts">无更多文章</div>';
  }

  // 跳转到推文详情页面
  function goToPostDetail(postId) {
    window.location.href = `/xiangqin.html?id=${postId}`;
  }

  // 更新分页按钮的状态
  function updatePaginationButtons() {
    const prevButton = document.getElementById('prevPage');
    const nextButton = document.getElementById('nextPage');

    prevButton.disabled = (currentPage === 1); // 第一页时禁用“上一页”
  }

  // 加载下一页数据
  function loadNextPage() {
    if (!isLoading) {
      isLoading = true;
      currentPage++;
      fetchPosts(currentPage, pageSize);
    }
  }

  // 加载上一页数据
  function loadPreviousPage() {
    if (!isLoading && currentPage > 1) {
      isLoading = true;
      currentPage--;
      fetchPosts(currentPage, pageSize);
    }
  }

  // 获取最新公告并显示在弹窗中
  // 获取今天的日期，用作标记的 key
  const todayDate = new Date().toISOString().split('T')[0]; // 格式为 YYYY-MM-DD

  // 获取本地存储中的公告查看标记
  function hasSeenAnnouncement() {
    const lastSeenDate = localStorage.getItem('announcementSeenDate');
    return lastSeenDate === todayDate; // 如果日期匹配，表示已经查看过公告
  }

  // 设置本地存储，标记为已经查看公告
  function markAnnouncementAsSeen() {
    localStorage.setItem('announcementSeenDate', todayDate);
  }

  // 获取最新公告并显示在弹窗中
  async function fetchLatestAnnouncement() {
    try {
      // 检查是否已经查看过公告，如果没有，才请求公告内容并展示
      if (hasSeenAnnouncement()) {
        return; // 如果当天已经看过公告，不再请求公告
      }

      const response = await fetch('/api/v1/announcements/get', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const result = await response.json();

      if (result.code === 200 && result.data) {
        // 显示公告内容
        const announcement = result.data;
        document.getElementById('announcementContent').innerText = announcement.content;
        document.getElementById('announcementTitle').innerText = announcement.title;
        // 打开公告弹窗
        openAnnouncementModal();

        // 设置已查看公告标记
        markAnnouncementAsSeen();
      }
    } catch (error) {
      console.error("获取公告失败", error);
    }
  }

  // 打开公告弹窗
  function openAnnouncementModal() {
    document.getElementById('announcementModal').style.display = 'flex';
  }

  // 关闭公告弹窗
  function closeAnnouncementModal() {
    document.getElementById('announcementModal').style.display = 'none';
  }

  // 页面加载时调用 fetchPosts 获取第一页数据
  document.addEventListener('DOMContentLoaded', () => {
    checkLoginStatus(); // 检查教师登录状态
    fetchPosts(currentPage, pageSize); // 默认获取第一页，3条数据
    fetchLatestAnnouncement(); // 获取最新公告
  });
</script>

</body>
</html>
